﻿
using NB.MGJ.Common;
using NB.MGJ.Common.Helper;
using NB.MGJ.Common.MVC;
using NB.MGJ.Common.OSS;
//using NB.MGJ.Common.Helper.CommonModel;
//using NB.MGJ.FrameWork;
using NB.MGJ.Model;
using NB.MGJ.Service.AntiFake;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace NB.MGJ.Web.Controllers
{
    /// <summary>
    /// 机构管理相关
    /// </summary>
    /// =======================================================================
    /// 类名：ManagerController ManagerController的备注：ManagerController~1<br/>
    /// =======================================================================<br/>
    /// 更新履历<br/>
    /// 序号          更新日期          责任人           更新内容<br/>
    /// 001           2017/8/16         段扬             新建<br/>
    /// 002           2017/11/30        吕林             修改<br/>
    /// =======================================================================<br/>
    public partial class ManagerController : BaseController
    {
        AntiFakeQueryCodeLogService _codelog = new AntiFakeQueryCodeLogService();
        #region 机构管理

        #region 视图
        /// <summary>
        /// 表格界面
        /// </summary>
        /// <returns></returns>
        public ActionResult OrganizationalManage()
        {
            ViewBag.eid = LogOnUser.EnterpriseId;
            ViewBag.headid = LogOnUser.HeadId;
            ViewBag.rid = LogOnUser.AdminRoleID;
            return View();
        }
        /// <summary>
        /// 添加界面
        /// </summary>
        /// <returns></returns>
        public ActionResult AddOrganization()
        {
            //var fatherId = 0;//新增 父ID为0  默认为行业目录（即一级目录）
            //ViewData["ClassifyId"] = _productService.GetClassifySelectList(0, fatherId);
            ViewBag.eId = LogOnUser.EnterpriseId;
            ViewBag.HeadId = LogOnUser.HeadId;
            ViewBag.rid = LogOnUser.AdminRoleID;
            return View();
        }
        /// <summary>
        /// 编辑界面
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult EditOrganization(int? id = null)
        {
          Organization_Enterprise emodel=_mservice.GetEnterpriseModelId(id.Value);
          ViewBag.Enterprise = emodel;
            ViewBag.eId = LogOnUser.EnterpriseId;
            ViewBag.rid = _mservice.UserByEid(emodel.Code).AdminRoleID;
            return View();
        }

        public ActionResult OrganizationalShowData(int id)
        {
            ViewBag.or = _mservice.OrganizationalShowDataId(id);
            //ViewBag.or = model;
            return View();
        }

        /// <summary>
        /// 编辑权限
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult ConfigCompetence(string type, int? id)
        {
            ViewBag.rid = id;
            ViewBag.type = type;
            ViewBag.UserId = LogOnUser.UserID;
            return View();
        }
        #endregion

        #region 导出EXCEL
        public ActionResult ExeclExpors(string Osearch,string key,int Eform=0)
        {
            string where = "  ViewDel=0 AND   ID  not in(" + LogOnUser.EnterpriseId + ")  ";
            if (Eform != 0)
            {
                where += " and OrganizationForm=" + Eform + " ";
            }
            if (!string.IsNullOrWhiteSpace(Osearch))
            {
                where += " and EnterpriseName like '%" + Osearch + "%' ";
            }
            if (!string.IsNullOrWhiteSpace(key))
            {
                where += " and id In(" + key + ")";
            }
            if (LogOnUser.EnterpriseId != 1)
            {

                if (string.IsNullOrWhiteSpace(LogOnUser.JuniorEnterprise))
                {
                    where += " ID=" + LogOnUser.EnterpriseId;
                }
                else
                {
                    where += " and  ID in ( " + _mservice.GetSonEnterpriseStrArray(LogOnUser.EnterpriseId) + ") ";
                }
            }
            var model = _mservice.GetAllOrganization(where,key);
            var _byte_catch = Excel.Exprot<V_Organization>(model.ToList(),
             new string[] { "机构代码", "机构名称", "机构形式/类型", "上级机构", "负责人", "负责人手机", "座机电话", "状态", "省市区", "地址", "操作时间" },
             q =>
             {
                 return new object[] { 
		               q.Code,
		               q.EnterpriseName,
		               q.fName+"/"+q.tName,
		               q.SuperiorsOrganizationName,
		               q.PersonCharge,
		               q.PersonMobile,
	                   q.LandlinePhone,
		               q.ViewFlag==1?"启用":"禁用",
	                   q.PrivinceName,
		               q.Address,
		               q.CreateDate
				};
             }, "Organization");
            return File(_byte_catch, "application/octet-stream", string.Format("{0}.xls", DateTime.Now.ToString("yyyyMMddHHmmssfff")));
        }
        #endregion

        #region 机构分页
        public JsonResult GetOrganizationalInfo(string Osearch, int Eform = 0, int pageIndex = 1, int pageSize = 10)
        {
            //var userid = LogOnUser.UserID;
            //var enterid = LogOnUser.EnterpriseId;
            PagerModel pm = new PagerModel()
            {
                Page = pageIndex,
                PageSize = pageSize
            };
            // pm.Page = pageIndex;
            //pm.PageSize = 10;

            string where = " e.ViewDel=0 AND  e.ID  not in(" + LogOnUser.EnterpriseId + ")  ";
            if (Eform != 0)
            {
                where += " and OrganizationForm=" + Eform + " ";
            }
            if (!string.IsNullOrWhiteSpace(Osearch))
            {
                where += " and EnterpriseName like '%" + Osearch + "%' ";
            }
            if (LogOnUser.EnterpriseId != 1)
            {

                if (string.IsNullOrWhiteSpace(LogOnUser.JuniorEnterprise))
                {
                    where += "  e.ID=" + LogOnUser.EnterpriseId;
                }
                else
                {
                    where += " and e.ID in ( " + _mservice.GetSonEnterpriseStrArray(LogOnUser.EnterpriseId) + ") ";
                }
            }
            pm.StrCondition = where;
            //var modulePage = _mservice.GetOrganizationalInfoService(ref pm, Osearch);
            return Json(_mservice.GetOrganizationalInfoService(ref pm, Osearch));
        }

        #endregion

        #region 增
        /// <summary>
        /// 检查机构名称是否已在在
        /// </summary>
        /// <returns></returns>           
        public JsonResult CheckEnterparise(string EnterpriseName)
       {
            //var result = _mservice.GetByEnterparise(EnterpriseName);
            return Json(new
            {
                valid = _mservice.GetByEnterparise(EnterpriseName)
            });
        }

        public ActionResult AddEnterprise(HttpPostedFileBase file, string submitData, string Ename)//, string loginName, string pwd)
        {


            #region  将机构插入数据库 返回机构id
            string filePath = "";
            string fileName = string.Empty;
  
            if (file != null)
            {
                if (file.ContentLength > 0 && file.ContentLength != 945)
                {
                    string fileNames = Constant.GetGuid32+ System.IO.Path.GetFileName(file.FileName);
                    OssManager.Instance.PutObject(fileNames, file.InputStream);
                    filePath = OssManager.Instance.GetUrl(fileNames);
                }
            }
            //待修改
         Organization_Enterprise model = jsonHelper.JSONToObject<Organization_Enterprise>(submitData);
            model.CreateDate = DateTime.Now;
            model.ChangeLoginID = base.LogOnUser.UserID;
            model.ChangeLoginName = base.LogOnUser.LoginName;
            model.ChangeDate = DateTime.Now;
            model.Code = "0000";
            model.StartTime = DateTime.Now;



            model.ViewDel = 0;
            model.ViewFlag = 1;
            model.Img = filePath;
            model.SuperiorsOrganization = LogOnUser.EnterpriseId;
 
            //添加机构

            int Eid = _mservice.AddEnterpriseService(model);


            #endregion



            #region  修改机构code 和ID

            //

            //修改机构码
            model.ID = Eid;

            var enterModel = _mservice.GetEnterpriseModelId(LogOnUser.EnterpriseId);
            _mservice.UpdateEnterpriseAfterCreate(model, enterModel);

            #endregion


            #region   角色和用户绑定

           
            Random r = new Random();
            int uid = 0;
            //   string pwd = r.Next(100000, 999999).ToString();
            string pwd = "000000";
            if (Eid > 0 )
            {
                int rid = _mservice.GetRoleID(model.OrganizationForm.Value, model.OrganizationId.Value, LogOnUser.RoleID);
                List<int> roleIds = _mservice.GetRoleIdByKey(model.ServiceVersion);
                roleIds.Add(rid);
                uid = OrganAddUserInfo(model.Code, pwd, model, model.ID,rid);
                //角色和用户绑定
                foreach (var item in roleIds)
                {
                        AddRoleUserInfo(item, uid);
                }

                //新建扫码记录
                _codelog.CreateScanLogTb(model.Code);
            }

            #endregion



            return Json(new { state = uid, pwd = pwd, ename = model.EnterpriseName, LoginName = model.Code }, JsonRequestBehavior.AllowGet);
        }


        public ActionResult GetServiceVersionList ()
        {



            List<object> list = new List<object>();


            var slist=_mservice.GetServersionList();

            var currentEnterprise = _mservice.GetEnterpriseModelId(LogOnUser.EnterpriseId);


            if (currentEnterprise.ID == 1)
            {
              return Json(slist);
            }
            else if (currentEnterprise.HeadId == 1)
            {
                var serviceList=_mservice.GetServiceListByRoleIdListStr(currentEnterprise.ServiceVersion);
                return Json(serviceList);
            }
            else
            {
              var thisEnterprise = _mservice.GetEnterpriseModelId(Convert.ToInt32( currentEnterprise.SuperiorsOrganization));
              var serviceList = _mservice.GetServiceListByRoleIdListStr(thisEnterprise.ServiceVersion);
              return Json(serviceList);
            }



            //list.Add(new
            //{
            //    Key = 0,
            //    Value = "防伪"
            //});
            //list.Add(new
            //{
            //    Key = 1,
            //    Value = "溯源标准版"
            //});
            //list.Add(new
            //{
            //    Key = 2,
            //    Value = "溯源黄金版"
            //});
            //list.Add(new
            //{
            //    Key = 3,
            //    Value = "溯源钻石版"
            //});
            //list.Add(new
            //{
            //    Key = 4,
            //    Value = "窜货"
            //});
            //list.Add(new
            //{
            //    Key = 5,
            //    Value = "营销"
            //});


            //return Json(list, JsonRequestBehavior.AllowGet);

        }



        #region 添加机构 角色
        public int OrganAddRoleInfo(Organization_Enterprise model, int eid)
        {
            Sys_Role role = new Sys_Role();
            role.EnterpriseId = eid;
            role.RoleName = "系统管理员";
            //role.Remark =_mservice.GetEnterpriseForm((int)model.OrganizationForm ) + "管理员";
            role.Remark = _mservice.GetEnterpriseForm(model.OrganizationForm.Value) + "管理员";
            role.RoleType = 1;
            role.ViewFlag = 1;
            role.Sequence = eid;
            role.ViewDel = 0;
 
            //int ruelst= _mservice.OrganAddRoleInfoService(role);
            //return ruelst;
            return _mservice.OrganAddRoleInfoService(role);
        }
        #endregion

        #region 添加机构是调用 添加用户
        public int OrganAddUserInfo(string name, string pwd, Organization_Enterprise e, int eid,int rid)
        {
            L.EntityModel.Sys_User model = new L.EntityModel.Sys_User();
            model.ViewFlag = 1;
            model.ViewDel = 0;
            model.LoginName = name;
            model.Pwd = MD5Manager.Gen_MD5(pwd, true);//EDS3.DESEnCode(pwd);//研 cf
            model.EnterpriseId = eid;
            model.RealName = e.PersonCharge;
            model.ChangeDate = e.ChangeDate;
            model.ChangeLoginID = base.LogOnUser.UserID;
            model.ChangeLoginName = base.LogOnUser.LoginName;
            model.DisableTime = e.EndTime;
            model.Remark = e.EnterpriseName + "管理员";
            model.UserImg = "/Content/HomePage/home/head_portrait.png";
            model.Type = 1;
            model.AdminRoleID = rid;
            return _mservice.OrganAddUserInfoService(model);
            //if (entitye != null && entitye.ResultState == Enums.EnumResultState.Success)//成功时候记录
            //    LogBLL.Add(LogFrontBackTypeEnum.BackType, LogTypeNameEnum.Add, user.LoginName, user.RealName,
            //            LogOperatingDescriptionActionEnum.LODAE0, user.ButtonId, "");
        }
        #endregion

        #region 添加机构 绑定角色
        public int AddRoleUserInfo(int rid, int uid)
        {
            Sys_RoleUserInfo ru = new Sys_RoleUserInfo()
            {
                Uid = uid,
                Rid = rid
            };
            //ru.Uid = uid;
            //ru.Rid = rid;
            return _mservice.AddRoleUserInfoService(ru);
        }
        #endregion

        #endregion

        #region 删除
        public int DelOrganizational(int oeid)
        {
            //int result = _mservice.DelOrganizationalService(oeid);
            //return result;
            return _mservice.DelOrganizationalService(oeid);
        }
        #endregion

        #region 改
        public int updEnterprise(HttpPostedFileBase file,Organization_Enterprise model)
        {
            //DBHController dbh = new DBHController();
            model.CreateDate = DateTime.Now;
            model.StartTime = DateTime.Now;
            //int rulset = _mservice.updEnterpriseService(model);
            //return rulset;
            return _mservice.updEnterpriseService(model);
        }

        public ActionResult UpdateEnterprise(Organization_Enterprise model)
        {
            model.ChangeDate = DateTime.Now;
            model.ChangeLoginID = LogOnUser.UserID;
            model.ChangeLoginName = LogOnUser.LoginName;
            model.Remark = model.Remark ?? " ";
            model.Img = model.Img?? "/Content/webImgs/upLogo/cp_img_tj.png";
            model.Address = model.Address ?? " ";
            List<int> RoleId = _mservice.GetRoleIdByKey(model.ServiceVersion);
            int rid = _mservice.GetRoleID(model.OrganizationForm.Value, model.OrganizationId.Value, LogOnUser.RoleID);
            RoleId.Add(rid);
            //if (RoleId == "")
            //{
            //    return Json("0");
            //}
            //RoleId = RoleId.TrimEnd(',');

            string rolestr="";
            for (int i = 0; i < RoleId.Count; i++)
            {
                rolestr+=RoleId[i]+",";
            }
             rolestr=rolestr.Substring(0, rolestr.LastIndexOf(","));
            string[] c = rolestr.Split(',');
            var emodel=_mservice.GetEnterpriseModel_Eid(model.ID);
            int userId=_mservice.GetEnterpriseDefaultUserId(emodel);
            int result = _mservice.EditUserRoleService(userId, c);
            // model.StartTime = DateTime.Now;
            return Json(_mservice.updEnterpriseService(model));
        }

        #region 绑定下拉框  机构形式  机构类型
        public ActionResult GetFormBox(int rid)
        {
            //var result = _mservice.GetFormBoxService(LogOnUser.RoleID);
            //return Json(result);
            if (LogOnUser.AdminRoleID!=1)
            {
                rid = LogOnUser.AdminRoleID;
            }
   
            return Json(_mservice.GetFormBoxService(rid));
        }

        public ActionResult GetTypeBox(int ID)
        {
            //var result = _mservice.GetTypeService(LogOnUser.RoleID, ButtonId);
            //return Json(result);
         
            return Json(_mservice.GetTypeService(LogOnUser.AdminRoleID, ID));
        }
        #endregion
        #endregion

        //判断机构名称是否重复
        public ActionResult IsExistEnterprise(string Name,int id = 0)
        {
            if (LogOnUser.EnterpriseId != 1) return Json(_mservice.GetEModel(Name, id));
            return Json(true);
        }
        #endregion

        #region 权限控制

        #region 菜单显示

        /// <summary>
        /// 查询菜单 
        /// </summary>
        public JsonResult GetTableTree(int id)
        {
            //var result = _mservice.GetTableTreeService(LogOnUser.UserID);
            //return Json(result);
            return Json(_mservice.GetTableTreeService(LogOnUser.UserID));
        }

        #endregion

        #region 查询当前角色赋值
        public ActionResult GetRoleTree(int rid)
        {
            //List<sys_MenuRoleInfo> list= _mservice.GetRoleTreeService(rid);
            //return Json(list);
            return Json(_mservice.GetRoleTreeService(rid));
        }

        #endregion

        #endregion

    }
}
